package com.itany.utils;

import com.jcraft.jsch.*;

import java.io.InputStream;
import java.util.Properties;

public class SFTPUtils {

    /**
     *
     * @param host IP地址
     * @param username 用户名称
     * @param password 密码
     * @param port 端口
     * @param uploadDir 上传路径
     * @param in 文件流
     * @param fileName 新文件名称
     * @throws Exception
     */
    public  static void sftpPut(String host, String username, String password
            , Integer port, String uploadDir, InputStream in, String fileName)
            throws Exception{

        //获取会话
        JSch jSch = new JSch();
        Session session = jSch.getSession(username,host,port);
        session.setPassword(password);

        Properties properties = new Properties();
        //主机加密访问
        properties.put("StrictHostKeyChecking","no");
        session.setConfig(properties);
        session.connect();
        //获取上传管道
        Channel channel = session.openChannel("sftp");
        channel.connect();
        ChannelSftp sftp = (ChannelSftp)channel;
        //切换路径
        createDirCd(uploadDir,sftp);
        sftp.put(in,fileName);

        //关闭
        sftp.disconnect();
        channel.disconnect();
        session.disconnect();

 }

 public static void createDirCd(String path,ChannelSftp sftp)throws Exception{
        String[] str = path.split("/");
        for(int i=0;i<str.length;i++){
            SftpATTRS attrs = null;
             try {
                 attrs = sftp.stat(str[i]);
             }catch (Exception e){
               // e.printStackTrace();
             }
            if(attrs==null){
                sftp.mkdir(str[i]);
            }
            sftp.cd(str[i]);
        }

 }


   /* public static void main(String[] args)throws Exception {

        String newFile="123.txt";
        FileInputStream fileInputStream = new FileInputStream(new File("C:\\Users\\User\\Desktop\\uedtior配置.txt"));
        SFTPUtils.sftpPut("192.168.4.8","tyh","123",22,"test/file",fileInputStream,newFile);

    }
*/


}
